import datetime

from django.core.paginator import Paginator
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from user.models import User
from .models import Text
from .predict.train import test
def login(req):
    """
    跳转登录
    :param req:
    :return:
    """
    return render(req, 'login.html')


def register(req):
    """
    跳转注册
    :param req:
    :return:
    """
    return render(req, 'register.html')


def index(req):
    """
    跳转首页
    :param req:
    :return:
    """
    username = req.session['username']
    total_user = len(User.objects.all())
    date = datetime.datetime.today()
    month = date.month
    year = date.year
    total_text = len(Text.objects.all())
    total_lj=len(Text.objects.filter(status=1).all())
    return render(req, 'index.html', locals())


def login_out(req):
    """
    注销登录
    :param req:
    :return:
    """
    del req.session['username']
    return HttpResponseRedirect('/')


def personal(req):
    username = req.session['username']
    role_id = req.session['role']
    user = User.objects.filter(name=username).first()
    return render(req, 'personal.html', locals())

def wbfl(req):
    username = req.session['username']
    role_id = req.session['role']
    user = User.objects.filter(name=username).first()
    return render(req, 'text_classify.html', locals())
def get_text(request):
    """
       获取用户列表信息 | 模糊查询
       :param request:
       :return:
       """
    keyword = request.GET.get('name')
    page = request.GET.get("page", '')
    limit = request.GET.get("limit", '')
    role_id = request.GET.get('position', '')
    response_data = {}
    response_data['code'] = 0
    response_data['msg'] = ''
    data = []
    if keyword is None:
        results = Text.objects.all()
        paginator = Paginator(results, limit)
        results = paginator.page(page)
        if results:
            for user in results:
                if user.status == 1:
                    status = '是垃圾短信'
                else:
                    status = '非垃圾短信'
                record = {
                    "id": user.id,
                    "text": user.text,
                    "status": status,
                    "owner": user.owner,
                    'create_time': user.create_time.strftime('%Y-%m-%d %H:%m:%S'),
                }
                data.append(record)
            response_data['count'] = len(Text.objects.all())
            response_data['data'] = data
    else:
        users_all = Text.objects.filter(text_contains=keyword).all()
        paginator = Paginator(users_all, limit)
        results = paginator.page(page)
        if results:
            for user in results:
                if user.status == 1:
                    status = '是垃圾短信'
                else:
                    status = '非垃圾短信'
                record = {
                    "id": user.id,
                    "text": user.text,
                    "status": status,
                    "owner": user.owner,
                    'create_time': user.create_time.strftime('%Y-%m-%d %H:%m:%S'),
                }
                data.append(record)
            response_data['count'] = len(users_all)
            response_data['data'] = data
    return JsonResponse(response_data)

def predict1(request):
    try:
        title = request.POST.get('text')
        results = test(title)
        Text.objects.create(
            text=title,
            status=results,
            owner=request.session['username'],
        )
        if results ==1:
            results = '是垃圾短信'
        else:
            results = '非垃圾短信'
        response_data = {'message': 'success','result':str(results)}
        return JsonResponse(response_data)
    except Exception as e:
        print(e)
        return JsonResponse({'message': '检测失败'}, status=401)
def wbgl(req):
    username = req.session['username']
    role = int(req.session['role'])
    user = User.objects.filter(name=username).first()
    return render(req, 'text.html', locals())



def del_text(request):
    """
    删除用户
    """
    user_id = request.POST.get('id')
    result = Text.objects.filter(id=user_id).first()
    try:
        if not result:
            response_data = {'error': '删除信息失败！', 'message': '找不到id为%s的用户' % user_id}
            return JsonResponse(response_data, status=403)
        result.delete()
        response_data = {'message': '删除成功！'}
        return JsonResponse(response_data, status=201)
    except Exception as e:
        response_data = {'message': '删除失败！'}
        return JsonResponse(response_data, status=403)